'use strict';

/* Controllers */
app.controller('landlordListMangeCtl', function($scope, $http, rest, $compile, $location, ngDialog, user, $state, $window, uiLoad, $rootScope, $ocLazyLoad, $timeout) {

    var token = $window.localStorage.getItem("token");
    var id = $window.localStorage.getItem("id");
    $scope.queryParams = {};
    $scope.checkStatus = {};
    $scope.decorateStatus = {};
    $scope.checkTypeArray = [{
        "name": "全部",
        "value": -1
    }, {
        "name": "未申请",
        "value": -2
    }, {
        "name": "申请中",
        "value": 0
    }, {
        "name": "申请成功",
        "value": 1
    }, {
        "name": "申请失败",
        "value": 2
    }, {
        "name": "补件",
        "value": 5
    }];

    $scope.lockTypeArray = [{
        "name": "全部",
        "value": -1
    }, {
        "name": "未安装",
        "value": 0
    }, {
        "name": "锁电安装中",
        "value": 3
    }, {
        "name": "锁电安装成功",
        "value": 4
    }];
    var tmpHouseIdArr = "";

    initDataTables();

    function initDataTables() {
        $scope.dataTableSettings = {
            "sAjaxSource": "/tenancy-sys/landlord/queryLandlordList",
            "bAutoWidth": true,
            "dom": "tipr",
            "aoColumns": [{
                    "mDataProp": "",
                    "sDefaultContent": "",
                    "sClass": "center handle-ck"
                }, {
                    "mDataProp": "createTime",
                    "sTitle": "申请时间",
                    "sDefaultContent": "",
                    "sClass": "center"
                }, {
                    "mDataProp": "name",
                    "sTitle": "房东名称",
                    "sDefaultContent": "",
                    "sClass": "center"
                }, {
                    "mDataProp": "companyName",
                    "sTitle": "企业名称",
                    "sDefaultContent": "",
                    "sClass": "center"
                }, {
                    "mDataProp": "mobile",
                    "sTitle": "房东手机号",
                    "sDefaultContent": "",
                    "sClass": "center"
                }, {
                    "mDataProp": "landlordType",
                    "sTitle": "房东性质",
                    "sDefaultContent": "",
                    "sClass": "center landlordType"
                },


                {
                    "mDataProp": "checkStatus",
                    "sTitle": "审核状态",
                    "sDefaultContent": "",
                    "sClass": "center landlordStatus"
                },

                {
                    "mDataProp": "operate",
                    "sTitle": "操作",
                    "sDefaultContent": "",
                    "sClass": "center handle-td operation"
                }
            ],
            "fnRowCallback": function(nRow, aData, iDisplayIndex) {
                var btnStr = "";

                // btnStr += " <a class='operation-btn'>\
                //                 <div class='operation-none' >\
                //                 <a href='javascript:' ng-click='viewLandList(\"" + aData.id + "\")'>申请详情</a>\
                //                 </div>\
                //             </a>";
                btnStr += "<a href='javascript:;' class='btn btn-apply' style='margin-right:10px;' ng-click='viewHouseDetails(\"" + aData.id + "\",$event)'>申请详情</a>";

                $(nRow).find(".handle-td").append($compile(btnStr)($scope));

                // var checkStr = "";
                // checkStr += '<input type="checkbox" data-index="' + iDisplayIndex + '" value="' + $scope.myDatas.result.list[iDisplayIndex].id + '" class="checkchild" />';
                // $(nRow).find(".handle-ck").append($compile(checkStr)($scope));

                $(nRow).find(".operation-btn").on('click', function() {
                    var sopt = $(this).parent().find(".operation-none");
                    if (sopt.css('display') == 'none') {
                        sopt.show();
                        $scope.isCoverBgShow = true;
                        $scope.$apply();
                    } else {
                        sopt.hide();
                        $scope.isCoverBgShow = false;
                        $scope.$apply();
                    }
                });

                var checkStr = "";
                checkStr += '<input type="checkbox" data-index=" iDisplayIndex " class="checkchild" />';
                $(nRow).find(".handle-ck").append($compile(checkStr)($scope));

                if (aData.checkStatus == "RETURNBACK") {
                    var statusStr = "回退补件";
                } else if (aData.checkStatus == "CHECKSUCCESS") {
                    var statusStr = "审核通过";
                } else if (aData.checkStatus == "CHECKFAILE") {
                    var statusStr = "审核未通过";
                } else {
                    var statusStr = "房东待审核";
                }

                $(nRow).find(".landlordStatus").empty().append(statusStr);

                if (aData.landlordType == "PERSON") {
                    var statusStr = "职业房东（个人）";
                } else if (aData.checkStatus == "ENTERPRISE") {
                    var statusStr = "职业房东（企业）";
                } else {
                    var statusStr = "业主（产权拥有）";
                }


                $(nRow).find(".landlordType").empty().append(statusStr);

                tmpHouseIdArr += aData.houseId + ",";
                if (iDisplayIndex >= 9) {
                    // console.log(tmpHouseIdArr);
                }
            },
            "fnDrawCallback": function(oSettings) {
                $scope.checkStatusValue = $scope.queryParams.checkStatus;
                if ("number" == typeof $scope.checkStatusValue) {
                    $scope.checkTypeArray.map(function(ele, index) {
                        if ($scope.checkStatusValue == ele.value) {
                            $scope.checkStatus.selected = ele;
                        }
                    })
                }
                $scope.decorateStatusValue = $scope.queryParams.decorateStatus;
                if ("number" == typeof $scope.decorateStatusValue) {
                    $scope.lockTypeArray.map(function(ele, index) {
                        if ($scope.decorateStatusValue == ele.value) {
                            $scope.decorateStatus.selected = ele;
                        }
                    })
                }

            },
            "fnServerParams": function(aoData) {


                if ($scope.checkStatus && $scope.checkStatus.selected) {
                    $scope.queryParams.checkStatus = $scope.checkStatus.selected.value
                }
                if ($scope.decorateStatus && $scope.decorateStatus.selected) {
                    $scope.queryParams.decorateStatus = $scope.decorateStatus.selected.value
                }
                aoData.push({
                    'name': 'queryParams',
                    'value': $scope.queryParams
                });

                return aoData;
            },
            "fnServerData": function(sSource, aData, fnCallback, dataTableObject) {
                //自定义给datatables传递的参数
                var obj = dataTableObject.oAjaxData,
                    _baseParams = {
                        'page': obj.iDisplayStart / obj.iDisplayLength + 1,
                        'rows': obj.iDisplayLength,
                        pointPerson: id,

                        'search': 'false',
                        'nd': '1494221804416',
                    };

                var __data = angular.extend({}, _baseParams, obj.queryParams);
                rest.decoJava({
                    type: "post",
                    url: sSource,
                    data: __data,
                    beforeSend: function(request) {
                        request.setRequestHeader("token", token);
                    },
                    success: function(data) {
                        $scope.myDatas = data;
                        var data1 = {
                            'aaData': data.result,
                            'sEcho': obj.sEcho,
                            'iTotalDisplayRecords': data.pager.recordCount,
                            'iTotalRecords': data.records,
                        };
                        fnCallback(data1);
                        $(dataTableObject.nScrollBody).css('overflow', 'visible');
                        $(dataTableObject.nScrollBody).css('margin-bottom', 60 + 'px');
                        $(".dataTables_scrollHead").css("overflow","visible");
                    }
                });

                //搜索 说明 只要是点击的搜索就让page为1 并且刷新datatables目的是回到第一页
                //说明 自定义搜索只需在点击搜索的时候改变下datatables传过去的参数 然后$scope.dataTable.fnClearTable()即可
                $scope.search = function() {
                    __data.page = 1;
                    $scope.dataTable.fnClearTable();
                }

            }
        }
    }

    $scope.initFinish = function(dataTable) {
        $scope.dataTable = dataTable;
    }

    //监听房间号
    $scope.$watch('_roomCode', function(newValue, oldValue) {
        $scope.queryParams.roomCode = newValue;
    })

    //监听小区名称
    $scope.$watch('_areaName', function(newValue, oldValue) {
        $scope.queryParams.areaName = newValue;
    })

    //监听详细地址
    $scope.$watch('_address', function(newValue, oldValue) {
        $scope.queryParams.address = newValue;
    })

    //全部选中和取消
    $scope.allMenu = function(e) {
        var This = angular.element(e.target);
        if (This.is(":checked")) {
            angular.element(".checkchild").prop("checked", true);
        } else {
            angular.element(".checkchild").prop("checked", false);
        }
    }



    $scope.queryUser = function() {
        if ($scope.queryParams.checkStatus && $scope.queryParams.checkStatus.selected) {
            var checkStatusCache = $scope.queryParams.checkStatus.selected;
            if ($scope.queryParams.checkStatus.selected) {
                $scope.queryParams.checkStatus = $scope.queryParams.checkStatus.selected.value
            }
            $scope.dataTable.fnClearTable();
            $scope.queryParams.checkStatus = {};
            $scope.queryParams.checkStatus.selected = {};
            $scope.queryParams.checkStatus.selected = checkStatusCache;
        } else if ($scope.queryParams.decorateStatus && $scope.queryParams.decorateStatus.selected) {
            var decorateStatusCache = $scope.queryParams.decorateStatus.selected;
            if ($scope.queryParams.decorateStatus.selected) {
                $scope.queryParams.decorateStatus = $scope.queryParams.decorateStatus.selected.value
            }
            $scope.dataTable.fnClearTable();
            $scope.queryParams.decorateStatus = {};
            $scope.queryParams.decorateStatus.selected = {};
            $scope.queryParams.decorateStatus.selected = decorateStatusCache;
        } else {
            $scope.dataTable.fnClearTable();
        }

    };

    $scope.viewLandDetails = function(id) {
        $window.localStorage.setItem('landlordId', id);
        $state.go('app.landlord.landlordDetails', {
            landlordId: id
        });
    }



    $scope.coverBgHide = function() {
        $('.operation-none').hide();
        $scope.isCoverBgShow = false;
        // $scope.$apply();
    }

});

app.controller('ContractTimeCtrl', function($scope) {
    $scope.today = function() {
        $scope.contractStartDate = "";
        $scope.contractEndDate = "";
    };

    $scope.closeAll = function() {
        $scope.openContractBeginDated =
            $scope.openContractEndDated = false;
    }

    $scope.openContractBeginDate = function($event) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.closeAll();
        $scope.openContractBeginDated = true;
    };
    $scope.openContractEndDate = function($event) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.closeAll();
        $scope.openContractEndDated = true;
    };

    $scope.dateOptions = {
        format: 'yyyy/MM/dd',
        startingDay: 1,
        class: 'datepicker'
    };

    $scope.format = 'yyyy/MM/dd';

    $scope.today();

    $scope.$watch('contractStartDate', function(newValue, oldValue) {
        if ("[object Date]" === Object.prototype.toString.call(newValue)) {
            $scope.$emit('contractDate.start', moment(newValue).format('YYYY/MM/DD'))
        } else if (null === newValue) {
            $scope.$emit('contractDate.start', '')
        }
    });
    $scope.$watch('contractEndDate', function(newValue, oldValue) {
        if ("[object Date]" === Object.prototype.toString.call(newValue)) {
            $scope.$emit('contractDate.end', moment(newValue).format('YYYY/MM/DD'))
        } else if (null === newValue) {
            $scope.$emit('contractDate.end', '')
        }
    });
});